package com.chindeo.h5.x5.web

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewParent
import android.webkit.WebView
import android.widget.AbsListView
import android.widget.HorizontalScrollView
import android.widget.ScrollView
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2

/**处理WebView和ViewPager2滑动冲突
 * Created by zqs on 2022/5/12
 */
class CustomWebView:WebView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    override fun onOverScrolled(scrollX: Int, scrollY: Int, clampedX: Boolean, clampedY: Boolean) {
        if (clampedX) {
            val viewParent  = findViewParentIfNeeds(this)
            viewParent?.requestDisallowInterceptTouchEvent(false);
        }
        super.onOverScrolled(scrollX, scrollY, clampedX, clampedY)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_DOWN) {
            val viewParent = findViewParentIfNeeds(this)
            if (viewParent != null){
                viewParent?.requestDisallowInterceptTouchEvent(true);
            }
        }
        return super.onTouchEvent(event)
    }

    private fun findViewParentIfNeeds(tag:View): ViewParent? {
        val parent = tag.parent ?: return null
        if (parent is ViewPager ||parent is ViewPager2|| parent is AbsListView || parent is ScrollView || parent is HorizontalScrollView) {
            return parent;
        } else {
            if (parent is View) {
                findViewParentIfNeeds(parent);
            } else {
                return parent;
            }
        }
        return parent;

    }

}